//
//  LSZTabBar.swift
//  醒浪微博
//
//  Created by 雷顺哲 on 16/7/9.
//  Copyright © 2016年 LSZ. All rights reserved.
//

import UIKit
//必须继承 NSObjectProtocol
protocol LSZTabBarDelegate: NSObjectProtocol {
    func didSelectedComposeButton()
}

class LSZTabBar: UITabBar {
    
//    定义闭包
    var composeButtonClosure: (() -> ())?
//    定义代理属性
    weak var lszDelegate: LSZTabBarDelegate?
    
    // MARK:懒加载创建button
    private lazy var composeButton: UIButton = {
        let button = UIButton()
//        添加点击事件
        button.addTarget(self, action: "composeButtonAction", forControlEvents: .TouchUpInside)
        
//        设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
//        设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
//        设置button的大小跟图片相等
        button.sizeToFit()
        
        return button
    }()
    
    override init(frame: CGRect){
        super.init(frame: frame)
        
//        添加视图
        addSubview(composeButton)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//    设置layout
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        composeButton.centerX = width * 0.5
        composeButton.centerY = height * 0.5
        
//        设置个坐标,记录循环的是第几个系统的按钮
        var index = 0
//        自己计算的每个按钮的宽度
        let itemWidth = width / 5
        
        for value in subviews {
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                value.width = itemWidth
                
                value.x = itemWidth * CGFloat(index)
                if (index == 1){
                    index++
                }
                
                index++
            }
        }
    }
    
//    按钮的点击事件
    @objc private func composeButtonAction()  {
        
//        闭包调用
        composeButtonClosure?()
        
//        代理调用
        lszDelegate?.didSelectedComposeButton()
        
    }
}
